<?php

namespace app\common\library;

use Exception;
use Intervention\Image\ImageManager;

/**
 * 海报生成
 */
class Poster
{
	public $data = [];
	public $baseTpl = "";
	public $image = null;
	public $dirRoot = "";
	public $oss;
	public function __construct($data)
	{
		$this->data = $data;
		if(empty($data['uid']) || empty($data['tpl']) || empty($data['qrcode_url'])){
			return false;
		}
		$this->dirRoot = ROOT_PATH."public";
		$this->baseTpl = \fast\Utils::toMedia($data['tpl']);
		$this->manager = new ImageManager(array('driver' => 'gd'));
		$this->oss = Aliyun::getOss();
		$this->ossPath ='uploads/poster/' . md5($this->data['uid'].$this->data['tpl'].$this->data['qrcode_url']) . '_' . $this->data['uid'] . '.png';
	}
	/**
	 * 生成海报图
	 */
	public function run()
	{
		if (!$this->oss->isExists($this->ossPath)) {
			$dir = dirname($this->ossPath);
			if (!$this->oss->isExists($dir)) {
				$this->oss->mkDir($dir);
			}
			$poster = $this->getPoster();
			return $this->oss->uploadOs($this->ossPath, $poster->stream('jpg', 85)->getContents());
		}else {
			return $this->oss->getUrl($this->ossPath);
		}
	}
	/**
	 * 生成海报入口
	 * @return Image|string
	 * @throws Exception
	 */
	public function getPoster() {
		$poster = $this->generateTpl();
		$poster = $this->updateQrcode($poster);
		return $poster;
	}
	/**
	 * 生成海报
	 */
	private function generateTpl()
	{
		// 打开基础模板
		$goodsTpl = $this->manager->make($this->baseTpl)->resize(750, 940);
		return $goodsTpl;
	}
	/**
	 * 添加二维码
	 */
	private function updateQrcode($poster)
	{
		$qrImage = $this->getQrImage($this->data['qrcode_url']);
		$poster->insert($qrImage, 'top-left', 122, 220);
		return $poster;
	}
	/**
	 * @param $qrcode_url
	 * @param int $size
	 * @return \Intervention\Image\Image
	 */
	public function getQrImage($qrcode_url) {
		$qrCode = new \Endroid\QrCode\QrCode($qrcode_url);
		$qrCode->setMargin(0);
		$qrCode->setSize(500);
		$qrCode->setErrorCorrectionLevel('medium');
		$qrImage = $this->manager->make($qrCode->writeString());
		return $qrImage;
	}
}
